package GUI;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Iterator;

import javax.swing.JPanel;

import Plants.PowerPlant;
import Plants.PowerPlantListener;
import SmartGrid.SmartGrid;

public class EnergyGridCanvas extends JPanel{

	SmartGrid smartgrid;
	PowerPlant selectedPlant;
	
	/**
	 * Creates the canvas which displays the power lines and power plants on the main window
	 * @param smartgrid
	 */
	public EnergyGridCanvas(SmartGrid smartgrid)
	{
		super();
		super.setPreferredSize(new Dimension(Tools.Options.CANVAS_WIDTH, Tools.Options.CANVAS_HEIGHT));
		super.setBackground(Color.WHITE);
		this.smartgrid = smartgrid;
		Iterator<PowerPlant> plants = smartgrid.allPlants.values().iterator();
		while(plants.hasNext())
		{
			PowerPlant plant = plants.next();
			plant.getListeners().add(new PowerPlantListener()
			{

				@Override
				public void PowerPlantResponsibilitiesChanged(PowerPlant p) {
					EnergyGridCanvas.this.repaint();
				}

				@Override
				public void PowerPlantSupplyChanged(PowerPlant p) {
					EnergyGridCanvas.this.repaint();
				}

				@Override
				public void PowerPlantRepaint(PowerPlant p) {
					EnergyGridCanvas.this.repaint();
				}
				
			});
		}
		initMouseListener();
	}
	
	private void initMouseListener()
	{
		super.addMouseListener(new MouseAdapter(){
			
			@Override
			public void mouseClicked(MouseEvent e) {
				Iterator<PowerPlant> iter = smartgrid.allPlants.values().iterator();
				while(iter.hasNext())
				{
					PowerPlant plant = iter.next();
					if(plant.getBoundingBox().contains(e.getPoint()))
					{
						if(selectedPlant != null)
						{
							selectedPlant.setHighlighted(false);
							selectedPlant = null;
						}
						selectedPlant = plant;
						selectedPlant.setHighlighted(true);
						repaint();
						return;
					}
				}
				if(selectedPlant != null)
				{
					selectedPlant.setHighlighted(false);
					selectedPlant = null;
				}
				repaint();
			}
			
		});
	}
	
	@Override
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);
		
		Iterator<PowerPlant> plants = smartgrid.allPlants.values().iterator();
		while(plants.hasNext())
		{
			PowerPlant plant = plants.next();
			plant.paint(g);
		}
	}
	
}
